<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/15
 * Time: 上午11:01
 */

namespace Backend\Model;


use Think\Model;

class SettingsModel extends Model
{
    protected $connection = 'DB_CONFIG1';
    protected $table      = 'settings';

    //获取所有站点设置信息 setting
    public function getAllSiteSettings()
    {
      $where = array(
          'name' => array('like', 'setting_%')
      );
      $list  = $this->where($where)->select();
      if($list){
          $list = changeArrIndex($list,'name');
          foreach($list as $key => $val)
          {
              $list[$key]['data'] = unserialize($val['data']);
          }
      };
      return $list;
    }

    //获取Email的设置信息
    public function getEmailSettings()
    {
        $where = array(
            'name' => array('like', 'setting_email%')
        );
        $list  = $this->where($where)->select();
        if($list){
            $list = changeArrIndex($list,'name');
            foreach($list as $key => $val)
            {
                $list[$key]['data'] = unserialize($val['data']);
            }
        };
        return $list;
    }


    /**
     * 邮件发送函数
     */
    public function sendMail($to, $title, $content) {

            Vendor('PHPMailer.PHPMailerAutoload');
            $mail = new \PHPMailer(); //实例化
            $config = S('email_config');
            if(!$config)
            {
                //配置缓存
                $config = D('settings')->getEmailSettings();
                S('email_config', $config);
            }
            $mail->IsSMTP(); // 启用SMTP
            $mail->Host= $config['setting_email_host']['data']; //C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
            $mail->SMTPAuth = true; //启用smtp认证
            $mail->Username = $config['setting_email_username']['data']; //你的邮箱名
            $mail->Password = $config['setting_email_password']['data'] ; //邮箱密码
            $mail->From = $config['setting_email_username']['data']; //发件人地址（也就是你的邮箱地址）
            $mail->FromName = $config['setting_email_from']['data']; //发件人姓名
            $mail->AddAddress($to,"尊敬的客户");
            $mail->WordWrap = 100; //设置每行字符长度
            $mail->IsHTML(true); // 是否HTML格式邮件
            $mail->CharSet=$config['setting_email_charset']['data']; //设置邮件编码
            $mail->Subject =$title; //邮件主题
            $mail->Body = $content; //邮件内容
            return($mail->Send());
    }


    //站点缓存数据更新
    public function updateSiteCache()
    {
        $option = 'name like "%site%"';
        $list = M('settings')->where($option)->select();
        foreach($list as $key => $val)
        {
            $site[$val['name']] = unserialize($val['data']);
        }
        F('site_cache', $site);
    }

}